package com.app.megaprosoft.modyimcarcare;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import com.app.megaprosoft.DB.Ar;
import com.app.megaprosoft.DB.SQLiteDBClass;
import com.app.megaprosoft.DB.ServicePOS;
import com.app.megaprosoft.general.DateTime;
import com.app.megaprosoft.modyimcarcare.CarCare_GetCar.CustomTimePickerDialog;
import com.megaprosoft.modyimcarcare.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.TimePickerDialog;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.sax.StartElementListener;
import android.service.textservice.SpellCheckerService.Session;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

@SuppressLint("NewApi")
public class CarCare_Adapter_ListService extends ArrayAdapter<CarCare_ListService>   {

	protected static final String LOG_TAG = CarCare_Adapter_ListService.class.getSimpleName();
	
	private List<CarCare_ListService> 		items;
	private int 							layoutResourceId;
	private Context 						context;
	private CarCare_Adapter_ListService 	carcare_listservice_adapter;
	private AlertDialog 					StatusChangDialog,
											DetailDialog;
	private Button 							button_cancle,
											button_enter,
											button_service;
	private TextView 						tv_serviceid,
											tv_idcar,
											tv_car,
											tv_color,
											tv_tell,
											tv_time,
											tv_timein,
											tv_timeout,
											tv_pay;
	private String 							serviceid,
											carid,
											FFUserOID,
											DepCode,
											UserGroupOID,
											TabletCode;
	private CarCare_ServiceHolder 			holder;
//	Carcare_Main main;
	Intent newActivity;
	
	ServicePOS servicepos = new ServicePOS();
	Ar ar = new Ar();
	public CarCare_Adapter_ListService(Context context, int layoutResourceId, List<CarCare_ListService> items) {
		super(context, layoutResourceId, items);
		servicepos.setContext(context);
		ar.setContext(context);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.items = items;
		
		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		
		DetailDialog = new AlertDialog.Builder(context)
        .setView(inflater.inflate(R.layout.a_carcare_dialog_detailservice, null))
        .setCancelable(false)
        .create();
		
		DetailDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
				
				button_cancle 	= 	(Button) DetailDialog.findViewById(R.id.button_cancle);
				button_cancle.	setOnClickListener(text_cancle);
				button_enter  	= 	(Button) DetailDialog.findViewById(R.id.button_edituser);
				button_enter.setOnClickListener(edit);
				button_service  =	(Button) DetailDialog.findViewById(R.id.button_editservice);
				button_service.setOnClickListener(service);
				tv_serviceid 	=  	(TextView) DetailDialog.findViewById(R.id.tv_serviceid);
				tv_idcar 		= 	(TextView) DetailDialog.findViewById(R.id.tv_idcar);
				tv_car 			= 	(TextView) DetailDialog.findViewById(R.id.tv_car);
				tv_color 		= 	(TextView) DetailDialog.findViewById(R.id.tv_color);
				tv_tell 		= 	(TextView) DetailDialog.findViewById(R.id.tv_tell);
				tv_time 		= 	(TextView) DetailDialog.findViewById(R.id.tv_time);
				tv_timein 		= 	(TextView) DetailDialog.findViewById(R.id.tv_time_in);
				tv_timeout 		= 	(TextView) DetailDialog.findViewById(R.id.tv_timeout);
				
				tv_pay			= 	(TextView) DetailDialog.findViewById(R.id.tv_pay);
				
				String data[][];
				String data2[][];
				try {
					data = servicepos.SelectAll_ServicePOS("", getServiceid(),"");
					
					tv_serviceid.setText(data[0][1]);
					if(data[0][2].equals("")){
						tv_idcar.setText("ไม่ระบุ");
					}else{
						tv_idcar.setText(data[0][2]);
					}
					if(data[0][5].equals("")){
						tv_timein.setText("รอรับรถ");
					}else{
						tv_timein.setText(data[0][5]+" น.");
					}
					if(data[0][6].toString().equals("00:00")){
						tv_time.setText("รอรับรถ");
					}else{
						tv_time.setText(data[0][6]+" น.");
					}
					if(data[0][9].equals("")){
						tv_timeout.setText("ไม่ระบุ");
					}else{
						tv_timeout.setText(data[0][9]+" น.");
					}
					if(data[0][10].equals("")){
						tv_pay.setText("0");
					}else{
						tv_pay.setText(data[0][13]+" บาท");
					}
					
					try{
						data2 = ar.SelectAll_ArFF("",data[0][3],"");
						if(data2[0][64].equals("") || data2[0][64].equals(null)){
							tv_car.setText("ไม่ระบุ");
						}else{
							tv_car.setText(data2[0][64]);
						}
					}catch(Exception e){
						tv_car.setText("");
					}
					try{
						data2 = ar.SelectAll_ArFF("",data[0][3],"");
						if(data2[0][62].equals("") || data2[0][62].equals(null)){
							tv_color.setText("ไม่ระบุ");
						}else{
							tv_color.setText(data2[0][62]);
						}
					}catch(Exception e){
						tv_color.setText("");
					}
					try{
						data2 = ar.SelectAll_ArFF("",data[0][3],"");
						if(data2[0][16].equals("") || data2[0][16].equals(null)){
							tv_tell.setText("ไม่ระบุ");
						}else{
							tv_tell.setText(data2[0][16]);
						}
					}catch(Exception e){
						tv_tell.setText("");
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		
	}

	public static class CustomTimePickerDialog extends TimePickerDialog{
		 
        public static final int TIME_PICKER_INTERVAL=1;
        private boolean mIgnoreEvent=false;

        public CustomTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
        super(context, callBack, hourOfDay, minute, is24HourView);
        	
        }
 
        @Override
        public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
            super.onTimeChanged(timePicker, hourOfDay, minute);
            if (!mIgnoreEvent){
                minute = getRoundedMinute(minute);
                mIgnoreEvent=true;
                timePicker.setCurrentMinute(minute);
                mIgnoreEvent=false;
            }
        }
        
        public static  int getRoundedMinute(int minute){
             if(minute % TIME_PICKER_INTERVAL != 0){
                int minuteFloor = minute - (minute % TIME_PICKER_INTERVAL);
                minute = minuteFloor + (minute == minuteFloor + 1 ? TIME_PICKER_INTERVAL : 0);
                if (minute == 60)  minute=0;
             }
            return minute;
        }
    }
	
	private CustomTimePickerDialog.OnTimeSetListener timeSetListener = new CustomTimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        	String time = String.format("%02d", hourOfDay) + ":" +String.format("%02d", minute);
        	servicepos.UpdateServicePOS_TimeEnd(getServiceid(), time, "0");
//        	Toast.makeText(getContext(),getServiceid() +" : "+ time,Toast.LENGTH_SHORT).show();	
        }
        
        
	};
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		holder = null;
		 
		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		row = inflater.inflate(layoutResourceId, parent, false);
		if(position%2!=0){
			row.setBackgroundColor(Color.rgb(135, 206, 235));
		}else{
			row.setBackgroundColor(Color.rgb(255, 254, 238));
		}
//		row.setOnClickListener(Itemclick);
		
		holder = new CarCare_ServiceHolder();
		holder.carcareService = items.get(position);
		
//		holder.check.setTag(holder.carcarePayment);
		holder.numrow = (TextView)row.findViewById(R.id.number);
//		setOnCheckedChangeListener(holder);
		holder.serviceid = (Button)row.findViewById(R.id.serviceid);
		
		holder.idgetcar = (TextView)row.findViewById(R.id.idgetcar);
//		
		holder.timestart = (TextView)row.findViewById(R.id.timestart);
		holder.timeend = (TextView)row.findViewById(R.id.timeend);
		holder.servicestatus = (Button)row.findViewById(R.id.servicestatus);
		holder.uploadstatus = (ImageView)row.findViewById(R.id.uploadstatus);
		
		setOnCheckedChangeListener(holder);
		
		row.setTag(holder);

		setupItem(holder);
		return row;
	}

	private void setupItem(CarCare_ServiceHolder holder) {
//		holder.uploadstatus.setChecked(holder.carcareService.isUploadstatus());
		holder.numrow.setText(String.valueOf(holder.carcareService.getNumrow()));
		holder.serviceid.setText(holder.carcareService.getServiceid());
		holder.idgetcar.setText(String.valueOf(holder.carcareService.getIdgetcar()));
		holder.timestart.setText(String.valueOf(holder.carcareService.getTimestart()));
		holder.timeend.setText(String.valueOf(holder.carcareService.getTimeend()));
		holder.servicestatus.setText(String.valueOf(holder.carcareService.getServicestatus()));
//		holder.servicestatus.setCompoundDrawablePadding(R.drawable.b100);
		String update = holder.carcareService.getUploadstatus().toString();
		if(update.equals("1")){
			holder.uploadstatus.setImageResource(R.drawable.checktrue);
//			setImageDrawable(R.drawable.checktrue);
		}else{
			holder.uploadstatus.setImageResource(R.drawable.checkfalse);
//			holder.uploadstatus.setImageDrawable(R.drawable.checkfalse);
		}
	}

	public static class CarCare_ServiceHolder {
		
		CarCare_ListService carcareService;
		TextView numrow;
		Button serviceid;
		TextView idgetcar;
		TextView timestart;
		TextView timeend;
		Button servicestatus;
		ImageView uploadstatus;
	}
	
	private void setOnCheckedChangeListener(final CarCare_ServiceHolder holder) {
//		holder.uploadstatus.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View arg0) {
//				// TODO Auto-generated method stub
//				 Toast.makeText(context,
//	        	    		"Your Selected Position : " ,
//	        	    			Toast.LENGTH_SHORT).show();	
//				notifyDataSetChanged();
//			}
//			
//		});
		holder.servicestatus.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
//				int getPosition = (Integer) v.getTag();
				setServiceid(holder.carcareService.getServiceid().toString());
				setCarid(holder.carcareService.getIdgetcar().toString());
				
				newActivity = new Intent(getContext(),Carcare_StatusChange.class);
				newActivity.putExtra("ServiceID", getServiceid());
				newActivity.putExtra("CarId", getCarid());
				newActivity.putExtra("Servicestatus", holder.carcareService.getServicestatus());
				v.getContext().startActivity(newActivity);
//				StatusChangDialog.show();
			}
		});
		holder.timeend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setServiceid(holder.carcareService.getServiceid().toString());
				Calendar calendar = GregorianCalendar.getInstance();
				CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(v.getContext(), timeSetListener, 
						calendar.get(Calendar.HOUR_OF_DAY), 
						calendar.get(Calendar.MINUTE), true);
				timePickerDialog.setTitle("เวลาเเล้วเสร็จโดยประมาณ");
				timePickerDialog.setIcon(R.drawable.timee);
				timePickerDialog.show();
			}
			
		});
		holder.serviceid.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setServiceid(holder.carcareService.getServiceid().toString());
				DetailDialog.show();
			}
			
		});
		
	}
		
		 private OnClickListener text_cancle = new OnClickListener() {
		        public void onClick(View v) {
		        	
		        	DetailDialog.dismiss();
		        	
		        }
		    };
		 
		    private OnClickListener edit = new OnClickListener() {
		        public void onClick(View v) {
		        	newActivity = new Intent(getContext(),CarCare_GetCar.class);
		        	
		        	newActivity.putExtra("ServiceId", getServiceid());
		        	newActivity.putExtra("MODE", "EDIT");
		        	v.getContext().startActivity(newActivity);
		        	
					DetailDialog.dismiss();
		        }
		    };
		    
		    private OnClickListener service = new OnClickListener() {
		        public void onClick(View v) {
		        	newActivity = new Intent(getContext(),Carcare_Service.class);
		        	String data[][];
		        	String ARCODE = "";
					try {
						data = servicepos.SelectAll_ServicePOS("", getServiceid(), "");
						newActivity.putExtra("FFUserOID", data[0][4]);// UserOID
			        	newActivity.putExtra("ArCode", data[0][3]);// ArCode
			        	newActivity.putExtra("POSDocOID", data[0][1]);// POSDocOID
			        	ARCODE = data[0][3];
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        	String data2[][];
					try {
						data2 = ar.SelectAll_ArFF( "",ARCODE,"");
						newActivity.putExtra("CarSize", data2[0][60]);// CarSize
			        	newActivity.putExtra("CarGroupOID", data2[0][63]);// CarGroupOID
			        	newActivity.putExtra("CarGroup", data2[0][64]);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        	v.getContext().startActivity(newActivity);
		        	
					DetailDialog.dismiss();
		        }
		    };
		    
			public String getServiceid() {
				return serviceid;
			}

			public void setServiceid(String serviceid) {
				this.serviceid = serviceid;
			}

			public String getCarid() {
				return carid;
			}

			public void setCarid(String carid) {
				this.carid = carid;
			}

}
			
			

